package com.ms.architecture.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

abstract class DataBindingActivity : AppCompatActivity() {

    private var mBinding: ViewDataBinding? = null

    protected abstract fun initViewModel();
    protected abstract fun getDataBindingConfig(): DataBindingConfig?

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        val dataBindingConfig = getDataBindingConfig()
        dataBindingConfig?.let {
            val binding: ViewDataBinding =
                DataBindingUtil.setContentView(this, it.getLayout())
            binding.lifecycleOwner = this
            binding.setVariable(
                it.getVmVariableId(),
                it.getStateViewModel()
            )
            val bindingParams = it.getBindingParams()
            var i = 0
            val length = bindingParams!!.size()
            while (i < length) {
                binding.setVariable(bindingParams.keyAt(i), bindingParams.valueAt(i))
                ++i
            }
            mBinding = binding
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding?.unbind()
        mBinding = null
    }
}